import React, { useState } from 'react';
import { Button, Modal, Upload, message, Spin } from 'antd';
import { useSetState } from 'ahooks';

import { TRAlert, TRDefault, TRMessage, PLoading } from '#/components/index.js';
import { DownloadOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import TRNotification from '#/utils/notification.js';
import planIcon from '@/assets/img/plan_icon.png';

import type { IPublishInfoDataType, IOptionType } from '../../../type';
import { ITitleType, IFileType } from '../../../type';
import { ShowSelect, ExplainTitle } from '../../../components';
import { titleMap } from '../../../dictionary';
import { upLoadFiles, postQueryTabMenuList, deleteFiles } from '../../../service';
import { getTabMenuOptions, ToFixed } from '../../../tool';
import styles from './index.less';

interface IProps {
  /**
   * 数据
   */
  record?: IPublishInfoDataType;
  onPress: (data: Record<string, any>) => void;
  onOk?: (params?: any) => void;
}

interface IFileDataType {
  fileId?: string;
  fileName?: string;
  fileType?: IFileType;
  fileSize?: number;
}

const ImportModalComponent = (props: IProps) => {
  const { onPress, record, onOk } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [threeSelectData, setThreeSelectData] = useState<any[]>([]);
  const [secondMenuOptions, setSecondMenuOptions] = useState<IOptionType[]>([]);
  const [tabMenuOptions, setTabMenuOptions] = useState<IOptionType[]>([]);
  const [firstMenuId, setFirstMenuId] = useState<string>();
  const [secondMenuId, setSecondMenuId] = useState<string>();
  const [tabMenuId, setTabMenuId] = useState<string>();
  const [videoInfo, setVideoInfo] = useSetState<IFileDataType>({});
  const [pdfInfo, setPdfInfo] = useSetState<IFileDataType>({});
  const disabled = !(
    firstMenuId &&
    (secondMenuOptions.length > 0 ? secondMenuId : true) &&
    (tabMenuOptions.length > 0 ? tabMenuId : true) &&
    (pdfInfo?.fileId || videoInfo?.fileId)
  );

  // 编辑状态处理数据
  const dealData = (recordData: IPublishInfoDataType, val: any[]) => {
    const _secondMenuOptions =
      val?.find((item) => item?.value === recordData?.firstMenuId)?.children || [];
    const _tabMenuOptions =
      _secondMenuOptions?.find((item: any) => item?.value === recordData?.secondMenuId)?.children ||
      [];
    if (recordData?.fileType === IFileType?.VIDEO) {
      setVideoInfo({
        fileId: recordData?.fileId,
        fileName: recordData?.fileName,
        fileType: recordData?.fileType,
        fileSize: recordData?.fileSize,
      });
    } else {
      setPdfInfo({
        fileId: recordData?.fileId,
        fileName: recordData?.fileName,
        fileType: recordData?.fileType,
        fileSize: recordData?.fileSize,
      });
    }
    setSecondMenuOptions(_secondMenuOptions);
    setTabMenuOptions(_tabMenuOptions);
    setFirstMenuId(recordData?.firstMenuId);
    setSecondMenuId(recordData?.secondMenuId);
    setTabMenuId(recordData?.tabMenuId);
  };

  // 初始化
  const fetchData = async () => {
    setLoading(true);
    setError(false);
    const res = await postQueryTabMenuList({
      haveInfo: false,
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _data = getTabMenuOptions(res?.data || []);
      setThreeSelectData(_data?.modalData || []);
      if (record) {
        dealData(record, _data?.modalData);
      }
      setError(false);
    } else {
      message.error(res?.message || '系统异常');
      setError(true);
    }
    setLoading(false);
  };

  // 取消按钮
  const _onCancel = async () => {
    if (isEdit) {
      const res = await TRAlert.show('当前工作将不被保存，继续执行此操作？');
      if (res.index === 1) {
        setVisible(false);
        onPress({ index: 0 });
      }
    } else {
      setVisible(false);
      onPress({ index: 0 });
    }
  };

  const _onOk = async () => {
    if (onOk) {
      setIsLoading(true);
      const _params: any = {
        id: record?.id,
        fileList:
          videoInfo?.fileId && pdfInfo?.fileId
            ? [{ ...videoInfo }, { ...pdfInfo }]
            : videoInfo?.fileId
            ? [{ ...videoInfo }]
            : [{ ...pdfInfo }],
        firstMenuId, //一级菜单ID
        firstMenuName: threeSelectData?.find((item) => item.value === firstMenuId)?.label, //一级菜单名称
        secondMenuId, //二级菜单ID
        secondMenuName: secondMenuOptions?.find((item) => item.value === secondMenuId)?.label, //二级菜单名称
        tabMenuId, //tab菜单ID
        tabMenuName: tabMenuOptions?.find((item) => item.value === tabMenuId)?.label, //tab菜单名称
      };
      const res: any = onOk && (await onOk(_params));
      if (res && res.statusCode === HttpCode.SUCCESS) {
        setVisible(false);
        onPress({ index: 1, statusCode: HttpCode.SUCCESS });
      }
      setIsLoading(false);
    }
  };

  const onChange = (e: any, key: string) => {
    if (key === 'firstMenuId') {
      setFirstMenuId(e);
      setSecondMenuId(undefined);
      setTabMenuId(undefined);
      setSecondMenuOptions(threeSelectData?.find((item) => item.value === e)?.children || []);
      setTabMenuOptions([]);
    } else if (key === 'secondMenuId') {
      setSecondMenuId(e);
      setTabMenuId(undefined);
      setTabMenuOptions(secondMenuOptions?.find((item) => item.value === e)?.children || []);
    } else {
      setTabMenuId(e);
    }
    setIsEdit(true);
  };

  const handleChange = async ({ file }: any, type: IFileType) => {
    if (file.status === 'removed' && type === IFileType.VIDEO) {
      const res = await deleteFiles({
        fileId: videoInfo?.fileId,
      });
      if (res && res?.statusCode === HttpCode.SUCCESS) {
        setVideoInfo({
          fileId: '',
          fileName: '',
        });
      } else {
        TRMessage.success('删除失败');
      }
    } else if (file.status === 'removed' && type === IFileType.PDF) {
      const res = await deleteFiles({
        fileId: pdfInfo?.fileId,
      });
      if (res && res?.statusCode === HttpCode.SUCCESS) {
        setPdfInfo({
          fileId: '',
          fileName: '',
        });
      } else {
        TRMessage.success('删除失败');
      }
    }
    setIsEdit(true);
  };

  const customRequest = async ({ file }: any, type: IFileType) => {
    if (file?.size && file?.size / 1024 / 1024 < 15) {
      const errorList = [];
      const fileList = [{ ...file, name: file?.name }];
      if (file.status !== 'uploading' && file.status !== 'removed') {
        PLoading.show('上传附件中...');
        const pdata = new window.FormData();
        pdata.append('file', file);
        pdata.append('fileName', file?.name);
        const res = await upLoadFiles(pdata);
        PLoading.dismiss();
        if (res && res?.statusCode === HttpCode.SUCCESS) {
          if (type === IFileType.VIDEO) {
            setVideoInfo({
              fileId: res?.uploadBody?.fileId,
              fileName: file?.name,
              fileType: type,
              fileSize: ToFixed(file?.size ? file?.size / 1024 / 1024 : 0, 2),
            });
          } else {
            setPdfInfo({
              fileId: res?.uploadBody?.fileId,
              fileName: file?.name,
              fileType: type,
              fileSize: ToFixed(file?.size ? file?.size / 1024 / 1024 : 0, 2),
            });
          }
          TRMessage.success('上传成功');
        } else {
          fileList[fileList?.length - 1].status = 'error';
          fileList[fileList?.length - 1].response = res?.message || '上传失败';
          errorList.push(res?.message || '上传失败');
        }
      }
      setIsEdit(true);
    } else {
      TRMessage.info('文件过大请重新上传');
    }
  };

  React.useEffect(() => {
    fetchData();
  }, [record]);

  const filterOption = (input: string, option: { value: any; label: any }) => {
    const { value, label } = option;
    return (
      value?.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
      label?.toLowerCase().indexOf(input.toLowerCase()) >= 0
    );
  };

  const footerRender = () => {
    return [
      <Button key="dtest1" onClick={_onCancel} loading={isLoading}>
        取消
      </Button>,
      <Button key="dtest2" type="primary" onClick={_onOk} loading={isLoading} disabled={disabled}>
        确定
      </Button>,
    ];
  };

  return (
    <Modal
      className={styles.modal}
      centered
      width={672}
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>导入资料</span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        {loading ? (
          <Spin />
        ) : error ? (
          <TRDefault type={'error'} message={'系统异常'} />
        ) : (
          <div className={styles.center}>
            <div className={styles.one}>
              <ShowSelect
                placeholder={'请选择'}
                showArrow={true}
                options={threeSelectData}
                showSearch={true}
                disabled={!!record?.id}
                value={firstMenuId}
                filterOption={filterOption as any}
                onChange={(e: any) => onChange(e, 'firstMenuId')}
                style={{ width: 200 }}
              />
              <ShowSelect
                placeholder={'请选择'}
                showArrow={true}
                options={secondMenuOptions}
                disabled={!secondMenuOptions?.length || !!record?.id}
                showSearch={true}
                value={secondMenuId}
                filterOption={filterOption as any}
                onChange={(e: any) => onChange(e, 'secondMenuId')}
                style={{ width: 200 }}
              />
              <ShowSelect
                placeholder={'请选择'}
                showArrow={true}
                options={tabMenuOptions}
                disabled={!tabMenuOptions?.length || !!record?.id}
                showSearch={true}
                value={tabMenuId}
                filterOption={filterOption as any}
                onChange={(e: any) => onChange(e, 'tabMenuId')}
                style={{ width: 200 }}
              />
            </div>
            {((record?.id && record?.fileType === IFileType.VIDEO) || !record) && (
              <div className={styles.two}>
                <div className={styles.title}>
                  <ExplainTitle
                    title={titleMap[ITitleType.IMPORT_VIDEO].title}
                    subTitle={titleMap[ITitleType.IMPORT_VIDEO].subTitle}
                  />
                </div>
                <div className={styles.fileContent}>
                  <Upload
                    customRequest={(e) => customRequest(e, IFileType.VIDEO)}
                    onChange={(e) => handleChange(e, IFileType.VIDEO)}
                    maxCount={1}
                    // @ts-ignore
                    fileList={
                      videoInfo?.fileId
                        ? [{ uid: videoInfo?.fileId, name: videoInfo?.fileName }]
                        : []
                    }
                    accept=".mp4"
                  >
                    {!videoInfo?.fileId && (
                      <Button type="primary" ghost icon={<DownloadOutlined />}>
                        导入
                      </Button>
                    )}
                  </Upload>
                </div>
              </div>
            )}
            {((record?.id && record?.fileType === IFileType.PDF) || !record) && (
              <div className={styles.three}>
                <div className={styles.title}>
                  <ExplainTitle
                    title={titleMap[ITitleType.IMPORT_FILE].title}
                    subTitle={titleMap[ITitleType.IMPORT_FILE].subTitle}
                  />
                </div>
                <div className={styles.fileContent}>
                  <Upload
                    customRequest={(e) => customRequest(e, IFileType.PDF)}
                    onChange={(e) => handleChange(e, IFileType.PDF)}
                    maxCount={1}
                    // @ts-ignore
                    fileList={
                      pdfInfo?.fileId ? [{ uid: pdfInfo?.fileId, name: pdfInfo?.fileName }] : []
                    }
                    accept=".pdf"
                  >
                    {!pdfInfo?.fileId && (
                      <Button type="primary" ghost icon={<DownloadOutlined />}>
                        导入
                      </Button>
                    )}
                  </Upload>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </Modal>
  );
};

class ImportModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ImportModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new ImportModal();
